package ch.bfh.mobicomp;

import java.util.LinkedList;
import java.util.List;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class LightEventListener implements SensorEventListener {
	private List<SensorListener> listener = new LinkedList<SensorListener>();
	private SensorManager manager = null;
	private float currentSensorValue;
	private float lastSensorValue;

	public void addLightActionListener(SensorListener listener) {
		this.listener.add(listener);

		refreshEventBinding();
	}

	public void removeLightActionListener(SensorListener listener) {
		this.listener.remove(listener);

		refreshEventBinding();
	}

	private void refreshEventBinding() {
		if (listener.size() > 0) {
			manager.registerListener((SensorEventListener) this,
					manager.getDefaultSensor(Sensor.TYPE_LIGHT),
					SensorManager.SENSOR_DELAY_FASTEST);
			Log.d("Light", "on");
		}
		else {
			manager.unregisterListener(this);
		}
	}

	public LightEventListener(SensorManager manager) {
		this.manager = manager;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		Log.d("Light", String.valueOf(event.values[0]));
		
		currentSensorValue = event.values[0];

		if (lastSensorValue != 0 && currentSensorValue != lastSensorValue) {
			if (listener != null)
				for (SensorListener l : listener)
					l.onSensorChanged();
		}

		lastSensorValue = currentSensorValue;
	}

}
